package com.team.star.utils.pwdutils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.team.star.dao.UserDAO;
import com.team.star.entity.pojo.User;
import com.team.star.entity.vo.UserVO;
import com.team.star.exception.ServiceExceptionHandler;
import com.team.star.utils.ResponseCode;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Aspect
@Component
public class PasswordEncryptDecryptAspect {
    @Autowired
    private UserDAO userDAO;

    @Pointcut("@annotation(com.team.star.utils.pwdutils.PasswordEncryptDecrypt)")
    public void passwordEncryptDecryptPointcut() {
    }

    @Around("passwordEncryptDecryptPointcut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        PasswordEncryptDecrypt annotation = method.getAnnotation(PasswordEncryptDecrypt.class);
        String type = annotation.type();

        Object[] args = joinPoint.getArgs();
        if (args.length > 0 && args[0] instanceof UserVO userVO) {
            String password = userVO.getPassword();

            switch (type) {
                case "encrypt":
                    // 加密密码
                    userVO.setPassword(PasswordUtils.encrypt(password));
                    break;
                case "decrypt":
                    // 查询数据库中的哈希密码
                    User user = userDAO.selectOne(
                            new QueryWrapper<User>()
                                    .eq("username", userVO.getUsername())
                    );
                    if (user == null) {
                        throw new ServiceExceptionHandler(ResponseCode.USER_NOT_EXIST);
                    }
                    //解密验证
                    if (!PasswordUtils.decrypt(password, user.getPassword())) {
                        throw new ServiceExceptionHandler(ResponseCode.PASSWORD_ERROR);
                    }
                    break;
            }
        }

        return joinPoint.proceed(args);
    }
}
